package net.pimpas.web.jsf.components.ajax.validate;

import java.util.List;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;

import net.pimpas.web.jsf.components.ajax.UIAjax;
import net.pimpas.web.jsf.components.message.UIMessage;
import net.pimpas.web.jsf.util.ComponentUtils;

public class UIAjaxValidate extends UIAjax {
	
	public static final String COMPONENT_TYPE			= UIAjax.COMPONENT_TYPE+".validate";
	public static final String COMPONENT_FAMILY			= UIAjax.COMPONENT_FAMILY+".validate";
	public static final String COMPONENT_RENDER_TYPE	= UIAjax.COMPONENT_RENDER_TYPE+".validate";
	

	@Override
	public String getRender() {
		// HACK to support
		UIComponent parent = this.getParent();
		String parentID = parent.getId();
		List<UIMessage> messages = ComponentUtils.getAllComponentsByClass(FacesContext.getCurrentInstance().getViewRoot(), UIMessage.class);
		UIMessage msg = null;
		for(UIMessage message : messages) {
			if(message.getFor().equals(parentID)) {
				msg = message;
				break;
			}
		}
		
		return (msg!=null) ? msg.getId() : super.getRender();
	}
	
	@Override
	public String getRendererType() {
		return COMPONENT_RENDER_TYPE;
	}

	@Override
	public String getFamily() {
		return COMPONENT_FAMILY;
	}
}